/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.conn;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author sriram
 */
public class tcpSockOpen {
    ServerSocket servSocket = null;
    tcpSockReadWrite sockRW = null;
    private boolean debugEnabled = false;

    public boolean startListen (InetAddress host, int port) {
        try {
            servSocket = new ServerSocket(port,-1,host);
            return true;
        } catch (IOException e) {
            if(debugEnabled) {
                System.out.print("Could not listen on: ");
                System.out.print(host+" ");
                System.out.println(port);
                System.err.println(e.getMessage());
            }
        }
        return false;
    }

    public boolean startListen (int port) {
        try {
            servSocket = new ServerSocket(port);
            return true;
        } catch (IOException e) {
            if(debugEnabled) {
                System.out.print("Could not listen on port: ");
                System.out.println(port);
                System.err.println(e.getMessage());
            }
        }
        return false;
    }
    
    public tcpSockReadWrite waitForAccept () {
        Socket clntSocket = null;
        try {
            clntSocket = servSocket.accept();
        } catch (IOException e) {
            System.out.print("Accept failed: ");
            System.err.println(e.getMessage());
        }
        if (clntSocket != null)
            sockRW = new tcpSockReadWrite(true, clntSocket);
        return sockRW;
    }
    
    public tcpSockReadWrite serverConnect(String hostname, int port) {
        Socket clntSocket = null;
        try {
            clntSocket = new Socket(hostname, port);
        } catch (IOException e) {
            if(debugEnabled) {
                System.out.print("Connection to Server failed: ");
                System.out.println(port);
                System.err.println(e.getMessage());
            }
        }
        if (clntSocket != null)
            sockRW = new tcpSockReadWrite(true, clntSocket);
        return sockRW;
    }
    
    public void closeSockets() {
        try {
            if(servSocket != null) servSocket.close();
        } catch (IOException e) {
            if(debugEnabled) {
                System.err.print("Error Closing server socket");
                System.err.println(e.getMessage());
            }
        }
    }
}
